package com.wmlive.hhvideo.heihei.mainhome.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.common.base.DcBaseActivity;
import com.wmlive.hhvideo.common.navigator.Navigator;
import com.wmlive.hhvideo.common.network.HttpConstant;
import com.wmlive.hhvideo.heihei.beans.main.Comment;
import com.wmlive.hhvideo.heihei.beans.main.CommentDataCount;
import com.wmlive.hhvideo.heihei.beans.main.RefreshCommentBean;
import com.wmlive.hhvideo.heihei.beans.main.VideoCommentResponse;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.mainhome.adapter.CommentListAdapter;
import com.wmlive.hhvideo.heihei.mainhome.fragment.RecommendFragmentNew;
import com.wmlive.hhvideo.heihei.mainhome.presenter.CommentListPresenter;
import com.wmlive.hhvideo.utils.MyClickListener;
import com.wmlive.hhvideo.utils.PopupWindowUtils;
import com.wmlive.hhvideo.widget.refreshrecycler.RefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import cn.wmlive.hhvideo.R;
import cn.wmlive.hhvideo.rxbuslib.RxBus2;
import cn.wmlive.hhvideo.rxbuslib.RxBusSubscribe;
import cn.wmlive.hhvideo.rxbuslib.ThreadMode;


/**
 * 评论列表
 */
public class CommentListActivity extends DcBaseActivity<CommentListPresenter> implements
        CommentListPresenter.ICommentListView,
        RefreshRecyclerView.OnLoadMoreListener,
        CommentListAdapter.OnCommentItemClickListener {

    @BindView(R.id.viewBlank)
    View viewBlank;
    @BindView(R.id.tvCount)
    TextView tvCount;
    @BindView(R.id.ivClose)
    ImageView ivClose;
    @BindView(R.id.recyclerView)
    RefreshRecyclerView recyclerView;
    @BindView(R.id.tvComment)
    TextView tvComment;
    @BindView(R.id.llCommentPanel)
    LinearLayout llCommentPanel;
    private CommentListAdapter commentListAdapter;
    private long videoId;
    private int commentCount;
    private int videoPosition;
    private PopupWindow popupWindow;
    private int videoType = RecommendFragmentNew.TYPE_RECOMMEND;
    private boolean hasFocusChanged = false;

    public static void startCommentListActivity(Context context, int videoType, int position, int count, long videoId) {
        Intent intent = new Intent(context, CommentListActivity.class);
        intent.putExtra("position", position);
        intent.putExtra("commentCount", count);
        intent.putExtra("videoType", videoType);
        intent.putExtra("videoId", videoId);
        context.startActivity(intent);

    }

    @Override
    protected CommentListPresenter getPresenter() {
        return new CommentListPresenter(this);
    }

    @Override
    protected void onSingleClick(View v) {
        switch (v.getId()) {
            case R.id.tvComment:
                if (AccountUtil.isLogin()) {
                    CommentActivity.startCommentActivity(this, true, videoPosition, videoId, null, 0);
                } else {
                    showReLogin();
                }
                break;
            case R.id.viewBlank:
            case R.id.ivClose:
                finish();
                break;
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_comment_list;
    }


    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        if (intent != null && intent.getLongExtra("videoId", 0) > 0) {
            RxBus2.get().register(this);
            changeDecorView(4);
            videoId = intent.getLongExtra("videoId", 0);
            commentCount = intent.getIntExtra("commentCount", 0);
            videoType = intent.getIntExtra("videoType", RecommendFragmentNew.TYPE_RECOMMEND);
            videoPosition = intent.getIntExtra("position", 0);
            viewBlank.setOnClickListener(this);
            tvComment.setOnClickListener(this);
            ivClose.setOnClickListener(this);
            commentListAdapter = new CommentListAdapter(new ArrayList<Comment>(), recyclerView);
            commentListAdapter.setCommentItemClickListener(this);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setAdapter(commentListAdapter);
            recyclerView.setOnLoadMoreListener(this);
            tvCount.setText(String.format(Locale.getDefault(), getString(R.string.stringCommentCount), 0));
            presenter.getCommentList(true, videoId);

            commentListAdapter.setEmptyStr(R.string.comment_null);

        } else {
            toastFinish();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onCommentListOk(boolean isRefresh, List<Comment> list, boolean hasMore) {
        commentListAdapter.addData(isRefresh, list, hasMore);
        tvCount.setText(String.format(Locale.getDefault(), getString(R.string.stringCommentCount), commentCount));
    }

    @Override
    public void onDeleteCommentOk(int position, long commentId, CommentDataCount countBean) {
        showToast("删除评论成功");
        dismissLoad();
        if (null != countBean) {
            commentCount = countBean.getComment_count();
            tvCount.setText(String.format(Locale.getDefault(), getString(R.string.stringCommentCount), commentCount));
            RxBus2.get().send(GlobalParams.EventType.TYPE_REFRESH_RECOMMEND_COMMENT_COUNT, new RefreshCommentBean(this.videoPosition, videoId, commentCount));
        }
        commentListAdapter.refreshItemDelete(position, commentId);
    }

    @Override
    public void onRequestDataError(int requestCode, String message) {
        dismissLoad();
        if (requestCode == HttpConstant.TYPE_COMMENT_DELETE) {
            showToast("删除评论失败");
        } else if (requestCode == HttpConstant.TYPE_COMMENT_LIST || requestCode == HttpConstant.TYPE_COMMENT_LIST + 1) {
            commentListAdapter.showError(requestCode == HttpConstant.TYPE_COMMENT_LIST);
        } else {
            super.onRequestDataError(requestCode, message);
        }
    }

    @Override
    public void onLoadMore() {
        presenter.getCommentList(false, videoId);
    }

    @Override
    public void onAvatarClick(long userId) {
        Navigator.getInstance().navigateToOtherUserHome(this, true, userId);
        finish();
    }

    @Override
    public void onNameClick(int position, Comment comment) {
        if (AccountUtil.isLogin()) {
            if (null != comment && comment.getUser_id() > 0) {
                if (AccountUtil.getUserId() == comment.getUser_id()) {//自己的评论，进入删除动作
                    showDeletePop(position, comment);
                } else {//别人的评论，进行评论
                    CommentActivity.startCommentActivity(this, true, videoPosition, videoId,
                            comment.getUser() != null ? comment.getUser().getName() : null,
                            comment.getUser() != null ? comment.getUser().getId() : 0);
                }
            } else {
                showToast(R.string.hintErrorDataDelayTry);
            }
        } else {
            showReLogin();
        }
    }

    private void showDeletePop(final int dataPosition, final Comment data) {
        View viewDelete = LayoutInflater.from(this).inflate(R.layout.ppw_delete_comment, null);
        viewDelete.findViewById(R.id.tvDelete).setOnClickListener(new MyClickListener() {
            @Override
            protected void onMyClick(View v) {
                loading();
                presenter.deleteComment(dataPosition, data.getId(), data.getOpus_id());
                if (null != popupWindow) {
                    popupWindow.dismiss();
                }
            }
        });
        viewDelete.findViewById(R.id.tvCancel).setOnClickListener(new MyClickListener() {
            @Override
            protected void onMyClick(View v) {
                if (null != popupWindow) {
                    popupWindow.dismiss();
                }
            }
        });
        popupWindow = PopupWindowUtils.createPopWindowFromBottom(recyclerView, viewDelete, 1.0f);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CommentActivity.COMMENT_REQUEST_CODE) {
                if (null != data && null != data.getSerializableExtra("result")) {
                    final VideoCommentResponse response = (VideoCommentResponse) data.getSerializableExtra("result");
                    if (null != response) {
                        if (null != response.getData_count()) {
                            commentCount = response.getData_count().getComment_count();
                            tvCount.setText(String.format(Locale.getDefault(), getString(R.string.stringCommentCount), commentCount));
                            recyclerView.scrollToPosition(0);
                            RxBus2.get().send(GlobalParams.EventType.TYPE_REFRESH_RECOMMEND_COMMENT_COUNT, new RefreshCommentBean(videoPosition, videoId, commentCount));
                        }
                        if (null != response.getComment()) {
                            commentListAdapter.insertData(0, new ArrayList<Comment>() {{
                                add(response.getComment());
                            }});
                        }
                    }
                }
            }
        }
    }

    @RxBusSubscribe(code = GlobalParams.EventType.TYPE_WORK_DELETED, threadMode = ThreadMode.MAIN)
    public void onWorkDeletedEvent(Long videoId) {
        if (this.videoId == videoId) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        RxBus2.get().unRegister(this);
        super.onDestroy();
    }
}
